const fs = require('fs')
const path = require('path')
const { defineConfig } = require('rollup')
const json = require('@rollup/plugin-json')
const alias = require('@rollup/plugin-alias')
const commonjs = require('@rollup/plugin-commonjs')
const typescript = require('@rollup/plugin-typescript')
const nodeResolve = require('@rollup/plugin-node-resolve')
const { devBuildOutputPath } = require('../config')
const replace = require('@rollup/plugin-replace')

const entryFile = path.resolve(__dirname, '../../src/cli/index.ts')
const testFile = path.resolve(__dirname, '../../src/cli/test.ts')
const outputDir = devBuildOutputPath

// 路径别名配置
const aliasConfig = require('./alias')

const tsconfig = require('./tsconfig')

const inputs = [entryFile]

if (fs.existsSync(testFile)) {
  inputs.push(testFile)
}

module.exports = defineConfig({
  watch: {
    buildDelay: 100,
    include: ['src/**'],
    clearScreen: true
  },
  input: inputs, // 入口文件路径
  output: {
    dir: outputDir,
    format: 'cjs', // 输出格式为CommonJS模块
    preserveModules: true, // 保留模块结构
    preserveModulesRoot: 'src', // 将保留的模块放在根级别的此路径下
    sourcemap: false, // 是否生成源映射文件
    exports: 'named'
  },
  plugins: [
    typescript(tsconfig),
    nodeResolve(),
    commonjs(),
    json(),
    // 路径别名
    alias(aliasConfig),
    replace({
      __env__: '"development"',
      preventAssignment: true
    })
  ],
  external: getModules()
})

// 获取 package.json 所有模块
function getModules() {
  const pkg = require('../../package.json')
  const modules = []

  if (typeof pkg.dependencies === 'object') {
    modules.push(...Object.keys(pkg.dependencies))
  }

  if (typeof pkg.devDependencies === 'object') {
    modules.push(...Object.keys(pkg.devDependencies))
  }

  return modules
}
